package com.bsg.upm.service;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsg.upm.constant.DictTypeConstants;
import com.bsg.upm.constant.SysConstants;
import com.bsg.upm.dto.BackupFileDto;
import com.bsg.upm.entity.ServEntity;
import com.bsg.upm.entity.SubServEntity;
import com.bsg.upm.exception.APIException;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.util.DateUtils;

/**
 * 备份文件业务处理类
 * 
 * @author HCK
 *
 */
@Service
public class BackupFileService extends BaseService {

	/**
	 * 获取服务备份文件列表
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return RespJson请求结果对象
	 * @throws APIException
	 *             API异常处理类
	 */
	public RespJson list(Map<String, Object> paramMap) throws APIException {
		try {
			JSONArray retJsonArray = new JSONArray();
			// 保存MGM服务备份文件信息
			JSONArray mgmBackupFiles = new JSONArray();
			// MGM备份文件查询参数
			Map<String, Object> mgmSearchMap = new HashMap<String, Object>();

			// 查询指定服务的备份文件
			if (paramMap.containsKey("servId")) {
				String servId = (String) paramMap.get("servId");
				ServEntity serv = servDao.getBase(servId);
				String siteId = serv.getOrder().getArea().getSite().getId();
				List<SubServEntity> subServs = serv.getSubServs();
				for (SubServEntity subServ : subServs) {
					if (subServ.getSubOrder().getDefinitionSubServ().getCanBackup()) {
						mgmSearchMap.put("mgmServId", subServ.getRelateId());
						JSONArray mgmBackupfiles = listBackupFileInfoFromMGM(siteId, mgmSearchMap);
						if (mgmBackupfiles != null) {
							mgmBackupFiles.addAll(mgmBackupfiles);
						}
					}
				}
				// 查询指定站点下的所有/指定用户的备份文件
			} else if (paramMap.containsKey("siteId")) {
				String siteId = (String) paramMap.get("siteId");
				if (paramMap.containsKey("owner")) {
					mgmSearchMap.put("owner", paramMap.get("owner"));
				}
				JSONArray mgmBackupfiles = listBackupFileInfoFromMGM(siteId, mgmSearchMap);
				if (mgmBackupfiles != null) {
					mgmBackupFiles.addAll(mgmBackupfiles);
				}
			}

			for (int i = 0; i < mgmBackupFiles.size(); i++) {
				JSONObject mgmBackupFileInfo = mgmBackupFiles.getJSONObject(i);
				BackupFileDto backupFileDto = buildShowDto(mgmBackupFileInfo);
				retJsonArray.add(backupFileDto);
			}

			return RespJsonFactory.buildOK(retJsonArray);
		} catch (Exception e) {
			logger.error("服务备份文件查询异常", e);
			throw new APIException("服务备份文件查询异常:" + e.getMessage());
		}
	}

	private JSONArray listBackupFileInfoFromMGM(String siteId, Map<String, Object> paramMap) throws APIException {
		String urlPattern = "/{0}/backupfiles?";
		String url = MessageFormat.format(urlPattern, SysConstants.MGM_VERSION);
		if (paramMap.containsKey("mgmServId")) {
			url += "service=" + paramMap.get("mgmServId") + "&";
		}
		if (paramMap.containsKey("owner")) {
			url += "tag=" + paramMap.get("owner") + "&";
		}
		if (url.endsWith("?")) {
			url = url.substring(0, url.lastIndexOf("?"));
		}
		if (url.endsWith("&")) {
			url = url.substring(0, url.lastIndexOf("&"));
		}
		RespJson httpRespJson = sendHttpGet(siteId, SysConstants.INTERFACE_TYPE_MGM, url);
		if (httpRespJson.getStatus() == HttpStatus.SC_OK) {
			return ((JSONArray) httpRespJson.getData());
		} else {
			throw new APIException(httpRespJson.getMsg());
		}
	}

	private BackupFileDto buildShowDto(JSONObject mgmBackupFileInfo) {
		BackupFileDto dto = new BackupFileDto();
		dto.setId(mgmBackupFileInfo.getString("id"));
		String path = mgmBackupFileInfo.getString("path");
		dto.setName(path.substring(path.lastIndexOf("/") + 1));
		String backupType = mgmBackupFileInfo.getString("type");
		String backupTypeDictCode = definitionCache.getDefinitionCodeFromCache(DictTypeConstants.BACKUP_TYPE,
				backupType);
		dto.setBackupType(dictTypeCache.getTextFromCache(DictTypeConstants.BACKUP_TYPE, backupTypeDictCode));
		dto.setSize(mgmBackupFileInfo.getLong("size"));
		Date createdAt = DateUtils.parseGoDate(mgmBackupFileInfo.getString("created_at"));
		dto.setCreateDateTime(DateUtils.dateTimeToString(createdAt));

		Date finishedAt = DateUtils.parseGoDate(mgmBackupFileInfo.getString("finished_at"));
		dto.setUptime(finishedAt.getTime() - createdAt.getTime());

		Date retention = DateUtils.parseGoDate(mgmBackupFileInfo.getString("retention"));
		dto.setExpire(DateUtils.dateTimeToString(retention));
		dto.setOwner(mgmBackupFileInfo.getString("tag"));
		dto.setRemark(mgmBackupFileInfo.getString("remark"));
		return dto;
	}

}
